package com.snake.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.snake.demo.entity.LoginUser;
import com.snake.demo.entity.User;
import com.snake.demo.mapper.MenuMapper;
import com.snake.demo.mapper.UserMapper;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Author: snake_skin
 * @Date: 2024/05/18/10:40
 * @Description:
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Resource
    UserMapper userMapper;

    @Resource
    MenuMapper menuMapper;
    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {

        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("user_name", userName);
        User user = userMapper.selectOne(qw);
        if (user == null) {
            throw new RuntimeException("用户名或密码错误");
        }
        // 根据用户查询权限信息 添加到LoginUser中
        // List<String> list = new ArrayList<>(Arrays.asList("test","admin"));
        List<String> perms = menuMapper.selectPermsByUserId(user.getId());

        // 将user封装成UserDetails返回
        return new LoginUser(user, perms);
    }
}
